package me.ahoukuse.koala.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mysql.cj.protocol.Message;
import lombok.extern.slf4j.Slf4j;
import me.ahoukuse.koala.dao.UserDao;
import me.ahoukuse.koala.po.User;
import me.ahoukuse.koala.service.CaptchaService;
import me.ahoukuse.koala.util.FileUtil;
import me.ahoukuse.koala.util.JwtUtil;
import me.ahoukuse.koala.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@RestController
@Slf4j
public class Login {

    @Autowired
    UserDao userDao;

    @Autowired
    CaptchaService captchaService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public JSONObject userLogin(String userName, String userPassword, String loginSessionId, Integer captcha) {
        JSONObject res;
        log.info("username = {}, userPassword = {}, loginSessionId = {}, captcha = {}", userName, userPassword, loginSessionId, captcha);
        Integer c = (Integer) redisTemplate.opsForValue().get("captcha:"+loginSessionId);
        if (c == null || Math.abs(captcha - c) > 2) {
            res = MessageUtil.msg(400, "验证码错误");
            res.put("data", "");
            return res;
        }
        User user = userDao.findByUserName(userName);

        if (user != null && userPassword.equals(user.getPassword())) {
            res = MessageUtil.msg(200, "success");
            res.put("data", JwtUtil.createToken(String.valueOf(user.getId())));
        } else {
            res = MessageUtil.msg(400, "用户名或密码错误");
            res.put("data", "");
        }
        return res;
    }

    @RequestMapping(value = "getCaptcha")
    public JSONObject getCaptcha() throws IOException {
        return captchaService.genCaptcha();
    }
}
